'use strict';
/* eslint-disable */
module.exports = async (ctx, next) => {
  const { helper, request: req } = ctx;

  const role = req.headers.platform;
  ctx.logger.info(
    `-------------------------${role}--${ctx.request.method}--${ctx.request.url}--`
  );
  ctx.logger.info(`body:`);
  ctx.logger.info(req.body);
  async function res() {
    await next();
    if (!ctx.body) {
      ctx.body = {
        code: 200,
      };
      return;
    }

    if (ctx.body.msg || (!!ctx.body.code && ctx.body.code !== 200)) {
      ctx.body = {
        code: ctx.body.code || 500,
        msg: ctx.body.msg || 'programer failed',
      };
      return;
    }
    ctx.body = {
      code: 200,
      data: ctx.body,
    };
  }

  // if (role === 'CLIENT') {
  ctx.logger.info('sign skip');
  return res();
  // }
  let sign = '';
  if (Object.keys(ctx.request.query).length > 0) {
    ctx.logger.info('query:', ctx.request.query);
  }
  if (Object.keys(ctx.request.body).length > 0) {
    ctx.logger.info('body', ctx.request.body);
    ctx.logger.info(
      'sign body data',
      JSON.stringify(req.body)
        .replace(/:(\d+?)([,}])/g, ':"$1"$2')
        .slice(0, 100)
    );
    sign = helper.encode(
      JSON.stringify(req.body)
        .replace(/:(\d+?)([,}])/g, ':"$1"$2')
        .slice(0, 100)
    );
  } else {
    ctx.logger.info(
      'sign query data',
      JSON.stringify(req.query)
        .replace(/:(\d+?)([,}])/g, ':"$1"$2')
        .slice(0, 100)
    );
    sign = helper.encode(
      JSON.stringify(req.query)
        .replace(/:(\d+?)([,}])/g, ':"$1"$2')
        .slice(0, 100)
    );
  }

  ctx.logger.info('server.sign', sign);
  ctx.logger.info('header.sign', req.headers.sign);

  if (sign !== req.headers.sign) {
    ctx.logger.info('sign failed');
    ctx.body = {
      code: 401,
    };
    return;
  }

  // ctx.logger.info('body:', ctx.body.dataValues || ctx.body);
};
